const nodeExcel = require('node-xlsx');
const fs=require('fs');
const path = require('path')

module.exports = {
    /**
     * 导出excel表格
     * @param {*} list 导出的数据
     * @param {*} fileName 导出文件名称
     * @param {*} filePath 文件存放的路径
     */
    toExcel:(list,fileName, filePath)=>{
        return new Promise(async (resolve,reject) =>{
            // 导出
            if(!filePath){
                filePath = path.join(__dirname,'../public/excel',fileName+'.xlsx')
            }else{
                filePath = path.join(fileName,fileName+'.xlsx')
            }
            const buffer = nodeExcel.build(list);// list 的格式也需要跟上述格式一致
            fs.writeFile(filePath, buffer, function (err) {
                if (err) {
                    resolve(false)
                    throw err;
                }
                resolve(filePath)
                console.log('Write to xls has finished');
            });
        }) 
    },

    /**
     * 导入excel表格
     * @param {*} file 
     */
    importExcel:file =>{
        return new Promise((resolve,reject) =>{
            const list = nodeExcel.parse(file)
            if(list){
                resolve(list)
            }else{
                resolve(false)  
            }
        })
    }
}

